import 'dart:async';

import 'package:get/get.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

class ScanController extends GetxController {
  Barcode? _barcode;
  late StreamSubscription<Object?>? _subscription;

  final MobileScannerController scanController = MobileScannerController(
    formats: const [BarcodeFormat.qrCode],
  );

  @override
  void onInit() {
    super.onInit();
    _subscription = scanController.barcodes.listen((BarcodeCapture barcodes) {
      _barcode = barcodes.barcodes.firstOrNull;
      if (_barcode == null) return;
      if (_barcode?.displayValue != null) {
        Get.back(result: _barcode?.displayValue);
        scanController.stop();
      }
    });
  }

  @override
  void onClose() async {
    super.onClose();
    unawaited(_subscription?.cancel());
    _subscription = null;
    await scanController.dispose();
  }
}
